package fetcher

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

// Post json 请求方式 ajax
func Post(data map[string]string) ([]byte, error) {
	if _, ok := data["url"]; !ok {
		panic("No Request Url！")
	}
	client := http.Client{}
	var contentType string
	if _, ok := data["content_type"]; !ok {
		contentType = "application/json"
	} else {
		contentType = data["content_type"]
	}
	jsonData, _ := json.Marshal(data)
	req, err := http.NewRequest(
		http.MethodPost,
		data["url"],
		strings.NewReader(string(jsonData)))
	req.Header.Add("Content-Type", contentType)
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("post failed, err:%v\n", err)
		return nil, err
	}
	defer resp.Body.Close()
	all, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("get resp failed,err:%v\n", err)
		return nil, err
	}
	return all, nil
}

func PostForm(data map[string]string) ([]byte, error) {
	if _, ok := data["url"]; !ok {
		panic("No Request Url！")
	}
	form := make(url.Values)
	for k, v := range data {
		form[k] = []string{v}
	}
	resp, _ := http.PostForm(data["url"], form)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	return body, nil

}
